﻿//========================================================= 
/**@file LinuxComIC_DevUpdater.h
 * @brief Linux下串口升级程序
 * 
 * @date 2017-01-21   11:57:24
 * @author Zhyioo 
 * @version 1.0
 */ 
//--------------------------------------------------------- 
#ifndef _LIBZHOUYB_LINUXCOMIC_DEVUPDATER_H_
#define _LIBZHOUYB_LINUXCOMIC_DEVUPDATER_H_
//--------------------------------------------------------- 
#include "COM_IC_DevUpdater.h"

#include "../../test_frame/linker/TestLinkerHelper.h"
using zhou_yb::application::test::TestLinkerHelper;

#include "../../tools/ParamHelper.h"
using zhou_yb::application::tools::ParamHelper;
//--------------------------------------------------------- 
namespace zhou_yb {
namespace application {
namespace updater {
//--------------------------------------------------------- 
/// Linux下串口设备检测升级状态连接器
template<class TComDevice>
struct LinuxComUpdateModeTestLinker : public TestLinker<TComDevice>
{
    //----------------------------------------------------- 
    /**
     * @brief 扫描串口,并发送升级切换指令
     * 
     * @param [in] dev 需要操作的设备
     * @param [in] arg 参数列表
     * - 参数:
     *  - Name : string 串口设备名称
     *  - Baud : uint 串口波特率
     * .
     * @param [in] printer 文本输出器
     */
    virtual bool Link(TComDevice& dev, IStringArguments& arg, TextPrinter& printer)
    {
        string devName;
        if(!arg.Get("Name", devName))
        {
            printer.TextPrint(TextPrinter::TextLogger, "缺少参数[Name]");
            return false;
        }

        if(!dev.Open(devName.c_str()))
        {
            printer.TextPrint(TextPrinter::TextLogger, "连接设备失败");
            return false;
        }

        uint baud = arg["Baud"].To<uint>(9600);
        uint upgradeBaud = 115200;

        TestLinkerHelper::LinkTimeoutBehavior(dev, arg, printer);

        printer.TextPrint(TextPrinter::TextLogger, "检测升级状态");
        dev.SetBaud(upgradeBaud);
        
        // 判断升级状态
        bool isUpgradeMode = ComUpdateModeSwitcher::IsUpgradeMode(dev);
        if(isUpgradeMode)
            return true;

        if(baud != upgradeBaud)
            dev.SetBaud(baud);

        if(!TestLinkerHelper::LinkCommand(dev, arg, printer))
            return false;

        printer.TextPrint(TextPrinter::TextLogger, "切换升级状态");
        ComUpdateModeSwitcher::ToUpgradeMode(dev);
        dev.Close();
        return false;
    }
    /// 关闭串口
    virtual bool UnLink(TComDevice& dev, TextPrinter&)
    {
        dev.Close();
        return true;
    }
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
} // namespace updater
} // namespace application
} // namespace zhou_yb
//--------------------------------------------------------- 
#endif // _LIBZHOUYB_LINUXCOMIC_DEVUPDATER_H_
//========================================================= 